package org.ioc.com.book_test1.controller;

import jakarta.servlet.http.HttpSession;
import org.ioc.com.book_test1.constant.Constants;
import org.ioc.com.book_test1.model.*;
import org.ioc.com.book_test1.service.BookInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookInfoController {
    @Autowired
    private BookInfoService bookInfoService;
    //1.添加图书
    @RequestMapping("/addBook")
    public String addBook(@RequestBody BookInfo bookInfo){
        //参数校验
        if (!StringUtils.hasLength(bookInfo.getBookName())||
            !StringUtils.hasLength(bookInfo.getAuthor())||
            !StringUtils.hasLength(bookInfo.getPublish())||
            bookInfo.getCount()==null||
            bookInfo.getPrice()==null||
            bookInfo.getStatus()==null
        ){
            System.out.println("传递参数错误");
        }

        Integer insert=bookInfoService.insert(bookInfo);
        return "添加图书成功"+insert;
    }
    //2.查询图书(根据前端页面响应)
    @RequestMapping("/selectBook")
    public Result<PageResult<BookInfo>> selectBook(PageRequest pageRequest, HttpSession session) throws Exception{
        //1.参数校验
        if (pageRequest.getPageNum()<=0){
            throw new Exception("参数错误");
        }
        UserInfo attribute = (UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);
        if (attribute==null||attribute.getId()<=0){
            return Result.nologin();
        }
        //2.数据查询,交给业务逻辑层,业务逻辑层交给数据层
        PageResult<BookInfo> list=bookInfoService.select(pageRequest);
        return Result.sucess(list);
    }
    //3.修改图书

    //查找图书之前应该获得图书信息
    @RequestMapping("/selectOne")
    public BookInfo selectOne(Integer id){
        BookInfo bookInfo=bookInfoService.selectOne(id);
        return bookInfo;
    }
    @RequestMapping("/updateBook")
    public Integer updateBook(BookInfo bookInfo){
        Integer update=bookInfoService.update(bookInfo);
        return update;
    }

    //删除
    @RequestMapping("/deleteBook")
    public Integer deleteBook(Integer id){
        Integer delete=bookInfoService.delete(id);
        return delete;
    }
    //批量删除
    @RequestMapping("/batchDeleteBook")
    public Integer batchDeleteBook(@RequestParam List<Integer> id){
        Integer batchDelete=bookInfoService.batchDelete(id);
        return batchDelete;
    }
}
